//
//  KFDMarketViewModel.m
//  KFD
//
//  Created by JIRENTIANXIANG on 6/10/15.
//  Copyright (c) 2015 kfd. All rights reserved.
//

#import "KFDMarketViewModel.h"
#import "KFDClient.h"
#import "NSDate+format.h"

#define TYPE_COUNT 14

@interface KFDMarketViewModel ()

@property (strong,nonatomic) NSTimer* marketPriceTimer;
@property (strong,nonatomic) NSTimer* diagramTimer;
@property (strong,nonatomic) NSMutableArray* lastTimeOfAllTypes;
@property (strong,nonatomic) NSMutableArray* diagramPointCountOfAllTypes;

@end

@implementation KFDMarketViewModel

-(instancetype)init
{
    if (self=[super init]) {
        self.currentPriceIndex=0;
        
        self.diagramPointsOfAllTypes=[[NSMutableArray alloc] init];
        for (int i=0; i<TYPE_COUNT; i++) {
            self.diagramPointsOfAllTypes[i]=[[NSMutableArray alloc] init];
        }
        
        self.lastTimeOfAllTypes=[[NSMutableArray alloc] init];
        for (int i=0; i<TYPE_COUNT; i++) {
            self.lastTimeOfAllTypes[i]=@0;
        }
        
        self.diagramPointCountOfAllTypes=[[NSMutableArray alloc] init];
        for (int i=0; i<TYPE_COUNT; i++) {
            self.diagramPointCountOfAllTypes[i]=@0;
        }
    }
    return self;
}

-(void)loadMarketPrices
{
    KFDClient* client=[KFDClient sharedClient];
    [client getMarketPriceWithSucessHandler:^(NSArray *marketPrices) {
        NSMutableArray* originalArr=marketPrices.mutableCopy;
        NSMutableArray* sortedArr=[NSMutableArray array];
        void(^filter)(NSString* type)=^(NSString* type){
            for (KFDMarketPrice* price in originalArr) {
                if ([price.typename isEqualToString:type]) {
                    [sortedArr addObject:price];
                    [originalArr removeObject:price];
                    break;
                }
            }
        };
        
        filter(@"hs300");
        filter(@"gold");
        filter(@"silver");
        filter(@"usoiln5");
        filter(@"ukoilq5");
        filter(@"usdx");
        
        [sortedArr addObjectsFromArray:originalArr];
        
        self.marketPrices=sortedArr;
        [[NSNotificationCenter defaultCenter] postNotificationName:KFDMarketPricesReadyNotification object:nil];
//        [self loadDiagramPointsForType:((KFDMarketPrice*)self.marketPrices.firstObject).typename completionHandler:completionHandler];
        if (self.marketPrices&&self.marketPrices.count>0) {
            [self loadDiagramPoints];
        }
    } failureHandler:^(KFDResponseBody *response) {
        
    }];
}

-(void)loadDiagramPoints
{
//    KFDMarketPrice* marketPrice=self.marketPrices[self.currentPriceIndex];
    [self loadDiagramPointsForTypeIndex:self.currentPriceIndex];
}

-(void)loadDiagramPointsForTypeIndex:(NSInteger)index
{
    if (!self.marketPrices||self.marketPrices.count==0) {
        return;
    }
    KFDClient* client=[KFDClient sharedClient];
    KFDMarketPrice* marketPrice=self.marketPrices[self.currentPriceIndex];
    NSNumber* lasttime=self.lastTimeOfAllTypes[index];
    [client getDiagramDataWithType:marketPrice.typename lastTime:lasttime successHandler:^(NSArray *diagramPoints,NSNumber* time) {
        
        if (lasttime.integerValue==0) {
            self.diagramPointCountOfAllTypes[index]=@(diagramPoints.count);
        }
        self.lastTimeOfAllTypes[index]=time;
        NSMutableArray* arr=[NSMutableArray arrayWithArray:self.diagramPointsOfAllTypes[index]];
        for (KFDDiagramPoint* point in diagramPoints) {
            [arr addObject:point];
        }
        while (arr.count>((NSNumber*)self.diagramPointCountOfAllTypes[index]).integerValue) {
            [arr removeObjectAtIndex:0];
        }
        self.diagramPointsOfAllTypes[index]=arr;
        
        if (index==0) {
            int i;
            KFDDiagramPoint* p2;
            KFDDiagramPoint* p1;
            float timeInterval = 0.0;
            for (i=1; i<arr.count; i++) {
                p2=arr[i];
                p1=arr[i-1];
                timeInterval=p2.date.timeIntervalSince1970-p1.date.timeIntervalSince1970;
                if (timeInterval>1000) {
                    break;
                }
            }
            if (timeInterval>1000) {
                self.breakPointTime=p1.date.timeIntervalSince1970;
                self.breakInterval=timeInterval;
                for (int j=i; j<arr.count; j++) {
                    KFDDiagramPoint* p=arr[j];
                    p.date=[NSDate dateWithTimeIntervalSince1970:p.date.timeIntervalSince1970-timeInterval];
                }
            }
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:KFDMarketDiagramViewShouldUpdateNotification object:nil];
    } failureHandler:^(KFDResponseBody *response) {
        
    }];
}

-(void)startMarketPriceTimer
{
    self.marketPriceTimer=[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(loadMarketPrices) userInfo:nil repeats:YES];
}

-(void)stopMarketPriceTimer
{
    [self.marketPriceTimer invalidate];
}

-(void)startDiagramTimer
{
    self.diagramTimer=[NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(loadDiagramPoints) userInfo:nil repeats:YES];
}

-(void)stopDiagramTimer
{
    [self.diagramTimer invalidate];
}

-(NSString*)selectedType
{
    KFDMarketPrice* marketPrice=self.marketPrices[self.currentPriceIndex];
    return marketPrice.typename;
}

@end
